#include <stdio.h>
#include <stdlib.h>
#include "debug.h"
#include "info.h"
#include "show.h"
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include "analyse_msg.h"

Mesg info1 , buf1 ,re_buf1 , send_buf1 , recv_buf1;

int main(int argc, char **argv)
{
	Mesg *info = &info1;
	Mesg *buf = &buf1;
	Mesg *re_buf = &re_buf1;
	Mesg *send_buf = &send_buf1;
	Mesg *recv_buf = &recv_buf1;


	int len = sizeof(Mesg);
	int type , cmd , ret;
	char string[512];
	if(3 != argc)
	{
		printf("Usage: %s <IP> <PORT>\n", argv[0]);
		return -1;
	}

	int sockfd = socket(AF_INET, SOCK_STREAM, 0);  
	if(-1 == sockfd)
		errsys("socket");

	struct sockaddr_in serveraddr = {0};
	serveraddr.sin_family = AF_INET;
	serveraddr.sin_port = htons(atoi(argv[2]));
	serveraddr.sin_addr.s_addr = inet_addr(argv[1]);//IPv4
	int lens = sizeof serveraddr;

	if(-1 == connect(sockfd, (struct sockaddr*)&serveraddr, lens))
		errsys("connect");
	while(1)
	{
		
		memset(buf, 0 , len);
		
		buf = client_login();

		write(sockfd , buf , len);//登录
		
		read(sockfd, re_buf , len);//读取登录结果
		

	
	
	    ret = analyse_ack(re_buf , string);  //分析登录结果
	
		printf("%s",string);//打印登录结果

		if( ret )
			continue;
		
		if(strcmp( re_buf->work_num,"000") == 0)//登录成功，显示对应菜单
		{
			admin_show();

			while(1){

				memset(send_buf , 0 , len);
				memset(recv_buf , 0 , len);
				
                send_buf = admin_mode(re_buf);          //admim操作
	//		   	printf("\n------------sendCMD:%d sendNUM:%s-------\n",send_buf->cmd,send_buf->work_num); 
			    write(sockfd , send_buf , len);//服务器分析
			                                              
			    read(sockfd , recv_buf , len); //读取分析结果    
				
	//		   	printf("\n------------sendCMD:%d sendNUM:%s-------\n",recv_buf->cmd,recv_buf->work_num); 
				analyse_ack(recv_buf , string);//解析结果      
				printf("---->\n");
				printf("%s\n" , string);//打印结果 
				
		    }    
		}       
		else     
		{       
			user_show();
			
			while(1){
				
				memset(send_buf , 0 , len);
				memset(recv_buf , 0 , len);
				
			//	printf("send:%s(num) %d(cmd)",re_buf->work_num,re_buf->cmd);
				send_buf = user_mode(re_buf);
			//	printf("send:%s(num) %d(cmd)",send_buf->work_num,send_buf->cmd);
			    write(sockfd , send_buf , len);//服务器分析
			                                              
			    read(sockfd , recv_buf , len); //读取分析结果    
				
				analyse_ack(recv_buf , string);//解析结果      

				printf("%s\n" , string);//打印结果               
					
			}
		}

	}
	
	close(sockfd);
}
